##This file produces Figure 2. Wrist-Measured Gunshot Example from Loeffler (2014), "Detecting Gunshots Using Wearable Accelerometers"

require(lattice)
require(latticeExtra)
require(extrafont)
##font_import()
loadfonts(device = "postscript")

##Open training data
avg_features<-read.csv("C:/Users/cloef/Box Sync/Gunshot Detection/Data/avg_features_201.csv")
avgfeatures <- na.omit(avg_features)
avgfeatures$time <- (avgfeatures$count-26)*0.3

par(omi=c(0.0278,0.0278,0.0278,0.0278))
par(mar = c(5,4,2,2)+ 0.1)

##Open postscript file
postscript("C:/Users/cloef/Box Sync/Gunshot Detection/Data/figure2.eps", paper = "special",height = 3.27, width = 3.27,
            family="Arial", horizontal = FALSE)

##Generate x-axis
av_x<-xyplot(avgfeatures$avg_ax~avgfeatures$time,lwd=0.5,type="l",xlab="ms",ylab="Gs",ylim=c(-10,10),xlim=c(-10,57.5),lty=1,col="black",
scales=list(
	x=list(
		at=seq(-10,60,10)),
    y=list(
      at=seq(-10,10,2))),
par.settings=list(layout.heights=list(top.padding=-1.5, bottom.padding=-0.5,key.axis.padding=-0.75),
	layout.widths=list(left.padding=0.5,right.padding=-2,ylab.axis.padding = -0.5)))

##Generate y-axis
av_y<-xyplot(avgfeatures$avg_ay~avgfeatures$time,lwd=0.5,type="l",ylim=c(-10,10),xlim=c(-10,57.5),lty=2,col="black",
par.settings=list(layout.heights=list(top.padding=-1.5, bottom.padding=-0.5,key.axis.padding=-0.75),
	layout.widths=list(left.padding=0.5,right.padding=-2,ylab.axis.padding = -0.5)))

##Generate z-axis
av_z<-xyplot(avgfeatures$avg_az~avgfeatures$time,lwd=0.5,type="l",ylim=c(-10,10),xlim=c(-10,57.5),lty=3,col="black",
par.settings=list(layout.heights=list(top.padding=-1.5, bottom.padding=-0.5,key.axis.padding=-0.75),
	layout.widths=list(left.padding=0.5,right.padding=-2,ylab.axis.padding = -0.5)))
trellis.par.set = simpleTheme(lty = 1:3,lwd=0.5)

##Combine axis plots with feature windows
print(av_x + av_y + av_z +
	layer_(panel.arrows(-7.5,-5,-0.3,-5, col = "black", 
                 length = 0.4, unit = "native", 
                 angle = 90,code=3)) +
	layer_(panel.arrows(-0.3,-5,1,-5, col = "black", 
                 length = 0.4, unit = "native", 
                 angle = 90,code=3)) +
	layer_(panel.arrows(1,-5,45,-5, col = "black", 
                 length = 0.4, unit = "native", 
                 angle = 90,code=3)) + 
	layer_(panel.text(c(-3.8,0.35,22.22),c(-5.9,-5.9,-5.9),labels=c("a","b","c"),fontsize=8)) +
	layer_(panel.rect(-0.3,-10,1,10, col = "lightgrey",border="lightgrey")) +
	layer(panel.key(c("x", "y", "z"), corner = c(0.96,0.96),
                   lines = TRUE,fontsize=6,border=TRUE, points = FALSE)) 
)
dev.off()